/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rlpw.swing;

import java.util.Comparator;
import javax.swing.JList;
import javax.swing.ListModel;
import javax.swing.event.ListDataListener;

/**
 *
 * @author weinpau
 */
public class JOList<T> extends JList implements View<T> {

    private Model<T> model;
    private Filter<T> filter;
    private Comparator<T> sorter;

    public JOList(Model<T> m) {
        setDataModel(m);
        setFilter(null);
        model.addView(this);

        setModel(new ListModel() {

            public int getSize() {
                return new FilteredList<T>(JOList.this).size();
            }

            public Object getElementAt(int index) {
                return new FilteredList<T>(JOList.this).get(index);
            }

            public void addListDataListener(ListDataListener l) {
                getDataModel().addListDataListener(l);
            }

            public void removeListDataListener(ListDataListener l) {
                getDataModel().removeListDataListener(l);
            }
        });

    }

    public JOList() {
        this(new DefaultModel<T>());
    }

    public void updateView() {
        revalidate();
        repaint();
    }

    public Model<T> getDataModel() {
        return model;
    }

    public void setDataModel(Model<T> model) {
        this.model = model;
        updateView();
    }

    public CheckModel<T> getCheckModel() {
        return null;
    }

    public SelectModel<T> getSelectModel() {
        return new ListSelectModel<T>(getDataModel(), getSelectionModel(), this);
    }

    public Filter<T> getFilter() {
        return filter;
    }

    public void setFilter(Filter<T> filter) {
        if (filter == null) {
            this.filter = new DefaultFilter<T>();
        } else {
            this.filter = filter;
        }

        updateView();
    }

    public void setSorter(Comparator<T> comp) {
        sorter = comp;
        updateView();
    }

    public Comparator<T> getSorter() {
        return sorter;
    }
}
